package com.lkd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lkd.dto.ChannelDTO;
import com.lkd.entity.Channel;
import com.lkd.entity.Sku;
import com.lkd.entity.VM;
import com.lkd.entity.VmType;
import com.lkd.mapper.ChannelMapper;
import com.lkd.mapper.SkuMapper;
import com.lkd.mapper.VmMapper;
import com.lkd.mapper.VmTypeMapper;
import com.lkd.service.ChannelService;
import com.lkd.service.VmService;
import com.lkd.vo.ChannelVO;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: Z.lx
 * @Date: 2025/8/23 08:50
 * @Description:
 **/
@Service
@AllArgsConstructor
public class ChannelServiceImpl extends ServiceImpl<ChannelMapper, Channel> implements ChannelService {
    private final ChannelMapper channelMapper;
    private final SkuMapper skuMapper;
    private final VmMapper vmMapper;
    private final VmTypeMapper vmTypeMapper;

    /**
     * 获取售货机货道详情
     */
    @Override
    @Transactional
    public List<ChannelVO> list(String innerCode) {
        VM vm = vmMapper.selectOne(Wrappers.<VM>lambdaQuery()
                .eq(VM::getInnerCode, innerCode));
        VmType vmType = vmTypeMapper.selectById(vm.getVmType());

        //用innerCode去查询channel
        QueryWrapper<Channel> qw = new QueryWrapper<>();
        qw.lambda().eq(Channel::getInnerCode, innerCode);

        List<Channel> channelList = channelMapper.selectList(qw);
        List<ChannelVO> channelVOList = new ArrayList<>();
        //遍历货道，获取每个货道的商品
        channelList.forEach(channel -> {
            ChannelVO channelVO = new ChannelVO();
            Sku sku = skuMapper.selectById(channel.getSkuId());
            BeanUtils.copyProperties(channel, channelVO);
            channelVO.setSku(sku);
            channelVOList.add(channelVO);
        });
        return channelVOList;
    }

    @Override
    public Boolean updateBatch(ChannelDTO channelDTO) {
        //1. 将dto转为po对象
        List<Channel> channelList = channelDTO.getChannelList().stream().map(dto -> {
            // 根据售货机编号和货道编号查询货道信息
            Channel channel = channelMapper.getChannelInfo(channelDTO.getInnerCode(), dto.getChannelCode());
            if (channel != null) {
                // 关联最新商品id
                channel.setSkuId(dto.getSkuId());
            }
            return channel;
        }).collect(Collectors.toList());

        //2. 批量修改货道
        return channelMapper.batchUpdateChannels(channelList);
    }
}
